<?php

namespace app\task\cron\mobile;

use yunwuxin\cron\Task;
use think\facade\Db;

/**
 * 话费返佣订单结算
 */
class SettleOrder extends Task
{
    /**
     * 5分钟执行1次
     */
    protected function configure()
    {
        // 分 时 日 月 周
        $this->expression = '*/5 * * * *';
    }

    /**
     * 执行指令.
     */
    protected function handle()
    {
        echo '开始话费佣金结算' . PHP_EOL;
        $lockKey = 'mobile_order_profit_lock_key';
        $lockVal = cache($lockKey);
        if ($lockVal) {
            echo '还在处理' . PHP_EOL;

            return true;
        }

        cache($lockKey, 1, 1200);

        Db::name('mobile_order')
            ->field('id, supplier_status, settle_type, agent_id, profit, amount,
            sale_price, settle_price, sub_order_id')
            ->where('status', 2)
            ->where('supplier_status', 3)
            ->where('settle_status', 2)
            ->where('settle_type', SETTLE_TYPE_PROFIT)
            ->chunk(60, function ($list) {
                $list = $list->toArray();
                if (empty($list)) {
                    return false;
                }

                $done = 0;
                foreach ($list as $order) {
                    if ($order['profit'] <= 0) {
                        Db::name('mobile_order')
                            ->where('id', $order['id'])
                            ->update([
                                'settle_status' => 1,
                            ]);
                        continue;
                    }

                    Db::startTrans();
                    try {
                        $res = Db::name('mobile_order')
                            ->where('id', $order['id'])
                            ->where('settle_status', 2)
                            ->update([
                                'settle_status' => 3,
                            ]);
                        if (!$res) {
                            Db::rollback();
                            continue;
                        }

                        $exists = Db::name('agent_balance_log')
                            ->where('type', BALANCE_MOBILE_PROFIT)
                            ->where('quote_id', $order['id'])
                            ->value('id');
                        if ($exists) {
                            continue;
                        }

                        $profitBalance = Db::name('agent')
                            ->where('id', $order['agent_id'])
                            ->value('profit_balance');
                        Db::name('agent')
                            ->where('id', $order['agent_id'])
                            ->inc('profit_balance', $order['profit'])
                            ->inc('total_profit', $order['profit'])
                            ->update([
                                'balance_last_updated_at' => date('Y-m-d H:i:s'),
                            ]);
                        Db::name('agent_balance_log')
                            ->insert([
                                'agent_id' => $order['agent_id'],
                                'type' => BALANCE_MOBILE_PROFIT,
                                'amount' => $order['profit'],
                                'old_balance' => $profitBalance,
                                'new_balance' => $profitBalance + $order['profit'],
                                'remark' => '话费充值：' . fen2yuan($order['amount']) . '元，销售价：' . fen2yuan($order['sale_price']) . '元，结算价：' . fen2yuan($order['settle_price']) . '元，利润：' . fen2yuan($order['profit']) . '元。订单号：' . $order['sub_order_id'],
                                'quote_id' => $order['id'],
                                'trade_no' => $order['sub_order_id'],
                            ]);
                        ++$done;
                        Db::commit();
                    } catch (\Exception $e) {
                        Db::rollback();
                        echo '报错了：' . $e->getMessage() . PHP_EOL;
                    }
                }

                echo '成功结算 ' . $done . ' 单' . PHP_EOL;
            });

        cache($lockKey, null);

        echo '话费佣金结算结束' . PHP_EOL;
    }
}
